//index.js
//获取应用实例
var app = getApp();
var goodslist=[];
var goods_spec={};
Page({
  data: {
    shop_list_select:[],
    shoppingCartList:[],
    goods:[],
    tabid:0,
    popup:0,
    popup2:0,
    data:{},
    choose_property_data: {},
    choose_spec: {},
    disabled: 0,
    spec_keys_str: '',
    config:{},
  },
  btn_cancel:function(){
    this.setData({ popup:0});
  },
  show_popup: function () {
    if (this.data.shoppingCartList.count){
      this.setData({ popup: 1 });
    }
  },

  bindChange:function(e){
    var value = e.detail.value;
    var shop_info = this.data.shop_list[value];
    this.setData({ shop_info: shop_info});
    wx.setStorageSync("shop_info", shop_info);
    this.getPageConfig();
    this.getcartByUserId();
  },
  onLoad: function (options) {
    // wx.navigateTo({
    //   url: '/mall/pages/tags',
    // })
    // return;
    var extConfigSync = app.getExtConfigSync();
    var that = this;
    var shop_info =  app.getShopInfo();
    var shop_list_select =[] ;
    for (var i in extConfigSync.shop_list){
      shop_list_select.push(extConfigSync.shop_list[i].name);
    }
    var index = "pages_index_" + shop_info.id;
    this.setData({ theme: extConfigSync.theme, shop_info: shop_info, shop_list: extConfigSync.shop_list, config: extConfigSync[index], shop_list_select: shop_list_select })
    app.getUserInfo(function(userInfo){
      that.getcartByUserId();
    })
    this.getPageConfig();
  },
  //页面配置
  getPageConfig:function(){
    app.api("mall/pages/getPageConfig", {
      page: "pages/index/index",
      shop_id: this.data.shop_info.id
    }, (res) => {
      if (res.code != 200) {
         app.alert(res.msg);
      }
      this.setData({ config: res.data });
      this.loadList();
    })
  },
//商品列表
  loadList:function(){
    var that = this;

    var config = this.data.config;
    if (!config.attrs){
      that.setData({
        goods: []
      });
      return ;
    }
 
    this.setData({ config: config}) ;

    for (let i in config.attrs){
      var params = config.attrs[i].params;
      app.api("mall/goods/get", params,  (res)=> {
        if (res.code != 200) {
          app.alert(res.msg);
        } 
        
        if (res.data && res.data.list ){
         goodslist[i] = res.data.list;
        }else{
         goodslist[i] = [];
        }
        var goods=[]
        for (var k in goodslist[i]){
          var item = goodslist[i][k];
          goods.push({
            default_img: item['default_img'],
            goods_name: item['goods_name'],
            origin_price: item['origin_price'],
            price: item['price'],
            total_stock: item['total_stock'],
            sub_title: item['sub_title'],
          })
        }
        that.data.goods[i] = goods;
        that.setData({
          goods: that.data.goods
        });
  
      })
    }
    

  },
  showTabs:function(e){
    wx.showLoading();
    var id = e.currentTarget.dataset.id;
    if (this.data.tabid == id) {
      return;
    }
    this.setData({ tabid: id });
    wx.hideLoading();
  },
  // 购物车
  getcartByUserId:function(){
    var that = this;
    app.api("mall/cart/getcartByUserId", { shop_id: this.data.shop_info.id }, function (res) {
      if (res.code != 200) {
        app.alert(res.msg);
      } else if (res.data) {
        that.setData({ shoppingCartList: res.data});
        // console.log("shoppingCartList",that.data.shoppingCartList);
      }
    })
  },
   //商品数量减
  minus:function(e){
    var id = e.currentTarget.dataset.id;
    var shoppingCartList = this.data.shoppingCartList;
    if (shoppingCartList.list[id].count<1){
      shoppingCartList.list[id].count =0;
    }else{
      shoppingCartList.list[id].count--;
    }
    this.setData({ shoppingCartList: shoppingCartList});
    this.addToCart({
      count: shoppingCartList.list[id].count,
      goods_spec_id: e.currentTarget.dataset.goods_spec_id,//  $(input).attr("goods_spec_id"),
      goods_id: e.currentTarget.dataset.goods_id,
    })

  },
   //商品数量加
  plus:function(e) {
    var id = e.currentTarget.dataset.id;
    var shoppingCartList = this.data.shoppingCartList;
    shoppingCartList.list[id].count++;
    this.setData({ shoppingCartList: shoppingCartList });
    this.addToCart({
      count: shoppingCartList.list[id].count,
      goods_spec_id: e.currentTarget.dataset.goods_spec_id,//  $(input).attr("goods_spec_id"),
      goods_id: e.currentTarget.dataset.goods_id,
    })
  },
   //商品数量
  changeCount: function(e) {
    var id = e.currentTarget.dataset.id;
    var count = e.detail.value;
    var shoppingCartList = this.data.shoppingCartList;
    shoppingCartList.list[id].count = count;
    this.setData({ shoppingCartList: shoppingCartList });
    this.addToCart({
      count: count,
      goods_spec_id: e.currentTarget.dataset.goods_spec_id,//  $(input).attr("goods_spec_id"),
      goods_id: e.currentTarget.dataset.goods_id,
    })

  },
  //加入购物车
   addToCart:function(post, callback){
    wx.showLoading();
    var that = this;
    app.api("/mall/cart/add", post, function (res) {
      wx.hideLoading();
      if (res.code != 200) {
        app.alert(res.msg);
      } else {
        callback ? callback(res) : '';
        that.setData({ shoppingCartList: res.data });
        if (res.data.count == 0) {
          that.btn_cancel();
        }
      }
    })
  },
  //清空购物车
  clearCart:function(){
    wx.showLoading();
    var that = this;
    app.api("mall/cart/clearCart", { shop_id: this.data.shop_info.id }, function (res) {
      if (res.code != 200) {
        app.alert(res.msg);
      } else {
        //phpkitApp.alert("恭喜,成功清空购物车!");
        wx.showToast({
          title: "恭喜,成功清空购物车!",
          icon:'success'
        });
        that.setData({ shoppingCartList: { nextText:'去结算'}});
        that.btn_cancel();
      }
      wx.hideLoading();
    })
  },
  //去结算
  settle_accounts:function(){
    wx.navigateTo({
      url: "/pages/checkout/index?shop_id=" + this.data.shop_info.id
    });
  },
  //选规格

  buyNow: function (e) {
    var postData = {};
    var item_id = e.currentTarget.dataset.item_id;
    var tab_id = e.currentTarget.dataset.tab_id;
    if (tab_id>-1 && item_id>-1){
      var data = goodslist[tab_id][item_id];
      goods_spec = data.goods_spec; 
      data.goods_spec={};
    }else if (this.data.data.id){
      var data = this.data.data;
    }else{
      app.alert("请选择商品");
      return ;
    }
   

    console.log("data",data);
    if (data.property_arr.length > 0 && this.data.choose_spec.spec_stock > 0) {
      postData.goods_id = this.data.choose_spec.goods_id;
      postData.goods_spec_id = this.data.choose_spec.id;
      //可以去结算
    } else if (data.property_arr.length == 0) {
      postData.goods_id = data.id;
    } else if (this.data.popup2==1){
      wx.showToast({
        title: '请选择商品规格',
        image: '/image/info.png'
      });
      return ; 
    }else {
      this.setData({data:data});
      this.chooseSpec();
      return;
    }
    //加入购车
    this.addToCart(postData, ()=>{
      wx.showToast({
        title: "成功加入购物车!",
        icon: 'success'
      });
    });
    this.hide_choose_goods();
  },
  hide_choose_goods:function(){
    goods_spec={};
    this.setData({ popup2: 0, data: {}, choose_spec: {}, choose_property_data:{}});
  },
  //弹出选规格
  chooseSpec:function(){
    this.setData({ popup2: 1 });
  },
  //选规格
  chooseProperty: function (e) {
    //console.log(e); 
    var property = e.currentTarget.dataset.property;
    var subProperty = e.currentTarget.dataset.subProperty;
    var choose_property_data = this.data.choose_property_data;
    choose_property_data[property] = subProperty;
    this.setData({ choose_property_data: choose_property_data });
    var arr = []
    for (var i in choose_property_data) {
      arr.push(choose_property_data[i]);
    }

    if (arr.length == this.data.data.property_arr.length) {
      this.setData({ spec_keys_str: arr.join(" ") });
      var l = arr.length;
      for (var j = 0; j < (5 - l); j++) {
        arr.push("");
      }
      // console.log(arr,arr);
      var spec_keys = arr.sort();
      var spec_keys_str = spec_keys.join("_");
      if (goods_spec[spec_keys_str] && goods_spec[spec_keys_str].spec_stock > 0) {
        this.setData({ choose_spec: goods_spec[spec_keys_str] });
        this.setData({ disabled: 0 });
      } else {
        wx.showToast({
          title: '已售空',
          image: '/image/info.png'
        });
        this.setData({ disabled: 1 });
      }
    }

    // console.log(this.data.choose_spec);
    //choose_spec
  },

  
 
})
